package com.TanNgee.demo4;

import java.util.concurrent.*;

/**
 * @author 陈毅
 * @create 2022/4/25 23:25
 * 练习异步计算结果
 */
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1 获取线程池对象
        final ExecutorService es = Executors.newCachedThreadPool();
        // 2 创建Callable类型的任务对象
        final Future<Integer> f = es.submit(new MyCall(1, 1));


//        test1(f);

        final boolean cancel = f.cancel(true);
        System.out.println("取消任务执行的结果" + cancel);

        final Integer integer;
        try {
            integer = f.get(1, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }
        System.out.println("任务执行的结果是" + integer);

    }

    /**
     * 正常测试流程
     *
     * @param f
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void test1(Future<Integer> f) throws InterruptedException, ExecutionException {
        // 3 判断任务是否已经完成
        final boolean done = f.isDone();
        System.out.println("第一次判断任务是否完成" + done);

        final boolean cancelled = f.isCancelled();
        System.out.println("第一次判断任务是否已经取消" + cancelled);

        final Integer integer = f.get();  //一直等待任务的执行，直到完成为止
        System.out.println("任务执行的结果是" + integer);

        final boolean done2 = f.isDone();
        System.out.println("第二次判断任务是否完成" + done2);

        final boolean cancelled2 = f.isCancelled();
        System.out.println("第二次判断任务是否已经取消" + cancelled2);
    }
}

class MyCall implements Callable<Integer> {
    // 通过构造方法传递两个参数
    private int a;
    private int b;

    public MyCall(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer call() throws Exception {
        final String name = Thread.currentThread().getName();
        System.out.println(name + "准备开始计算……");
        Thread.sleep(2000);
        System.out.println(name + "计算完成……");
        return a + b;
    }
}
